package com.example.homemanager.controller;
import com.example.homemanager.*;
import com.example.homemanager.model.LightCommand;
import com.example.homemanager.model.SensorData;
import com.example.homemanager.service.LightCommandService;
import com.example.homemanager.service.SensorDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*") // 允许跨域请求
public class SensorDataController {

    private final SensorDataService sensorDataService;
    private final LightCommandService lightCommandService;

    public SensorDataController(SensorDataService sensorDataService, LightCommandService lightCommandService) {
        this.sensorDataService = sensorDataService;
        this.lightCommandService = lightCommandService;
    }


    // 获取当前传感器数据
    @GetMapping("/sensors")
    public ResponseEntity<SensorData> getSensorData() {
        return ResponseEntity.ok(sensorDataService.getCurrentData());
    }

    // 更新传感器数据（由ESP32调用）
    @PostMapping("/sensors")
    public ResponseEntity<?> updateSensorData(@RequestBody SensorData sensorData) {
        log.info("Received POST request to /sensors");
        sensorDataService.updateSensorData(sensorData);
        return ResponseEntity.ok().build();
    }

    // 控制灯光
    @PostMapping("/light")
    public ResponseEntity<?> controlLight(@RequestBody Map<String, String> request) {
        String status = request.get("status");
        if ("on".equalsIgnoreCase(status) || "off".equalsIgnoreCase(status)) {
            sensorDataService.setLightStatus(status.toLowerCase());
            lightCommandService.setLatestLightCommand(status.toLowerCase());

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("status", status.toLowerCase());
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.badRequest().body("Invalid light status: " + status);
        }
    }
    @GetMapping("/light/command")
    public ResponseEntity<String> getLatestLightCommand() {
        return ResponseEntity.ok(lightCommandService.getLatestLightCommand());
    }
}